/*************************************
 * gpio2为0时NC供电，为1时停电
 *
 * *******************************/
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#define debugLevel
#ifdef debugLevel
#define debug(a) Serial.println(a)
#else
#define debug(a) ;
#endif

// const char *mqtt_server = "192.168.3.254";
const char *mqtt_server = "lubo1982.mycloudnas.com";
const char *mqttUser = "lu";
const char *mqttPassWd = "5891381";
const int port = 1883;
char pubTopic[20], subTopic[20], msgTopic[20];
unsigned long lastTime = 0;
WiFiClient espClient;
PubSubClient client(espClient);
String Host;
void callback(char *topic, byte *payload, unsigned int length)
{
    Serial.print("R[");
    Serial.print(topic);
    Serial.print("]:");
    String message;
    for (int i = 0; i < length; i++)
    {
        message += ((char)payload[i]);
    }
    Serial.println(message);

    // Switch on the LED if an 1 was received as first character
    // if (strcmp(topic, subTopic) == 0)

    if (message == "1")
    {
        digitalWrite(2, 0);
    }
    if (message == "0")
    {
        digitalWrite(2, 1);
    }
    client.publish(pubTopic, digitalRead(2) ? "Off" : "On");
    Serial.printf("T[%s]:%s\n", pubTopic, digitalRead(2) ? "1" : "0");
}

void reconnect()
{
    // Loop until we're reconnected

    while (!client.connect(Host.c_str(), mqttUser, mqttPassWd))
    {
        Serial.print("Attempting MQTT connection...");
        if (client.connect(Host.c_str(), mqttUser, mqttPassWd))
        {
            Serial.println("connected");
            // Once connected, publish an announcement...
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
    subscribe();
    client.publish(msgTopic, "MQTT server reconnected");
}
void subscribe()
{
    client.subscribe(subTopic);
}
void setup()
{
    uint8_t macAddr[6];
    WiFi.macAddress(macAddr);
    pinMode(2, OUTPUT);
    //   digitalWrite(2, 0);
    Serial.begin(115200);
    WiFiManager wifiManager;
    wifiManager.setTimeout(180);
    char ap[10];
    sprintf(ap, "Switch-%X%X%X", macAddr[3], macAddr[4], macAddr[5]);
    Host = "Switch" + macAddr[4] + macAddr[5];
    WiFi.hostname(Host.c_str());
    sprintf(pubTopic, "%X%X%X/Status", macAddr[3], macAddr[4], macAddr[5]);
    sprintf(subTopic, "%X%X%X/Cmd", macAddr[3], macAddr[4], macAddr[5]);
    sprintf(msgTopic, "%X%X%X/Msg", macAddr[3], macAddr[4], macAddr[5]);

    //   wifiManager.resetSettings();
    if (!wifiManager.autoConnect(ap))
    {
        Serial.println("failed to connect and hit timeout");
        delay(3000);
        ESP.reset();
        delay(5000);
    }
    Serial.println("WIFI connected");
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);
    reconnect();
}
void loop()
{
    if (!client.connected())
    {
        reconnect();
    }
    client.loop();
    if (millis() - lastTime >= 5000)
    {
        lastTime = millis();
        client.publish(pubTopic, digitalRead(2) ? "Off" : "On");
        Serial.printf("T[%s]:%s\n", pubTopic, digitalRead(2) ? "1" : "0");
    }

    //   client.publish(topic, Host.c_str());
}
